<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-col :span="1.5">
          <el-button size="mini" @click="isExport(2)">确认调出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="isExport(1)">确认调入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['eam:maintain:export']"
          >导出</el-button>
        </el-col>
        <el-input placeholder="单号" clearable style="width: 240px;margin-left: 10px;" @keyup.enter.native=""
          v-model="queryParams.allotOdd" size="mini" /> &nbsp;&nbsp;
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList()">查询</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allotList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="50">
        <template slot-scope="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="receiptsStatus" width="80">
        <template slot-scope="scope">
          <button class="but1" v-if="scope.row.receiptsStatus == 3">待审核</button>
          <button class="but2" v-if="scope.row.receiptsStatus == 2">已拒绝</button>
          <button class="but3" v-if="scope.row.receiptsStatus == 1">已审核</button>
          <button class="but4" v-if="scope.row.receiptsStatus == 4">已撤销</button>
        </template>
      </el-table-column>
      <el-table-column label="调拨单号" align="center" prop="allotOdd" width="170" >
          <template slot-scope="scope">
            <span style="font-size: 12px;">{{scope.row.allotOdd}}</span>
            <img class="img2" @click="flow(scope.row)" src="../../../assets/image/单据流水.png" />
          </template>
      </el-table-column>
      <el-table-column label="调拨日期" align="center" prop="allotDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.allotDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨部门" align="center" prop="exportDeptName" />
      <el-table-column label="调入部门" align="center" prop="foldDeptName" />
      <el-table-column label="存放位置" align="center" prop="locationName" />
      <el-table-column label="调出调入" align="center" prop="isExportFold">
        <template slot-scope="scope">
          <span v-if="scope.row.isExportFold == 1">已调入</span>
          <span v-if="scope.row.isExportFold == 2">已调出</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="preparedName" />
      <el-table-column label="制单时间" align="center" prop="preparedDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.preparedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" :disabled="scope.row.receiptsStatus != 3  || roles == 'common'"  @click="opneAudit(scope.row)">审核</el-button>
          <el-button size="mini" type="text" :disabled="scope.row.receiptsStatus != 1"  @click="hadReturn(scope.row)">撤回</el-button>
          <el-button size="mini" type="text"  @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button size="mini" type="text"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body style="margin-left: 80px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="调出部门" prop="exportDept">
              <el-select size="mini" v-model="form.exportDept">
                <el-option v-for="item in exportDeptList" :value="item.deptId" :label="item.deptName"
                  :key="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调入部门" prop="foldDept">
              <el-select v-model="form.foldDept" size="mini">
                <el-option v-for="item in foldDeptList" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="存放位置" prop="locationId">
              <el-select v-model="form.locationId" size="mini">
                <el-option v-for="item in locationList" :key="item.locationId" :label="item.locationName"
                  :value="item.locationId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="调拨日期" prop="allotDate">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.allotDate" size="mini"
                value-format="yyyy-MM-dd" style="width: 190px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-button size="mini">清空</el-button>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="div-yj">
              <div>
                <el-table :data="eamList" border>
                  <el-table-column label="序号" align="center" prop="index" :min-width="50">
                    <template #default="scope">
                      {{scope.$index + 1}}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" :min-width="60">
                    <template #default="scope">
                      <div class="box_scope">
                        <img src="../../../assets/image/加.png" @click="add" />
                        <img src="../../../assets/image/减.png" @click="minus(scope.$index)" />
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="选择资产" align="center" prop="xzasset" :min-width="120">
                    <!-- 使用作用域插槽自定义列内容 -->
                    <template slot-scope="scope">
                      <!-- 在作用域插槽内插入文本框 -->
                      <img class="img1" @click="open2Asset" src="../../../assets/image/搜索.png" />
                      <el-input :value="scope.row.assetCode"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="资产名称" align="center" prop="assetName" />
                  <el-table-column label="数量" align="center" prop="assetNum" />
                  <el-table-column label="金额" align="center" prop="price" />
                  <el-table-column label="规格" align="center" prop="asseSpec" />
                  <el-table-column label="型号" align="center" prop="model" />
                  <el-table-column label="报废日期" align="center" prop="scrapTime" />
                </el-table>

              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--选择资产-->
    <el-dialog :title="title2" :visible.sync="open2" width="1000px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-input placeholder="资产名称" maxlength="30" style="width: 200px;" v-model="asset.assetName" />&nbsp;
          <el-select placeholder="全部资产类型" v-model="asset.TypeId" clearable>
            <el-option v-for="item in typeList" :key="item.typeId" :label="item.typeName"
              :value="item.typeId"></el-option>
          </el-select>&nbsp;
          <el-select placeholder="全部存放位置" v-model="asset.locationId" clearable>
            <el-option v-for="item in locationList" :key="item.locationId" :label="item.locationName"
              :value="item.locationId"></el-option>
          </el-select>&nbsp;
          <el-button type="primary" icon="el-icon-search" size="mini" @click="open2Asset"
            style="height: 34px;">查询</el-button>
          <el-table :data="assetList" border style="padding-top: 10px;" @selection-change="assetSelectionChange"
            v-loading="loading1">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="资产名称" align="center" prop="assetName" />
            <el-table-column label="资产编码" align="center" prop="assetCode" :min-width="150" />
            <el-table-column label="资产类型" align="center" prop="typeName" />
            <el-table-column label="规格" align="center" prop="asseSpec" />
            <el-table-column label="型号" align="center" prop="model" />
            <el-table-column label="资产金额(元)" align="center" prop="price" />
            <el-table-column label="报废日期" align="center" prop="scrapTime" />
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页 -->
      <pagination class="fy" v-show="total2>0" :total="total2" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList()" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog :title="title4" :visible.sync="open4" width="620px" append-to-bod>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div>
          <el-form-item label="审核原因:" prop="nickName" style="height: 100px;">
              <el-input v-model="auditReason" type="textarea" maxlength="300" show-word-limit :rows="4"
                style="min-height: 100px;" > </el-input>
          </el-form-item>
        </div>
        <div style="text-align: right;margin-top: 10px;">
          <el-button @click="cancel4">取 消</el-button>
          <el-button type="warning" @click="audit(2)">不通过</el-button>
          <el-button type="primary" @click="audit(1)">通过</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 单据流水 -->
    <el-dialog :title="title3" :visible.sync="open3" width="620px" append-to-bod>
      <div
        style="width: 500px;height: 50px;border: 1px solid #006eff;margin-left: 50px;padding-left: 10px;background-color: #e6eff4;">
        <p><span>变更单号:&nbsp;</span><span style="font-weight: bold;">{{form.allotOdd}}</span></p>
      </div>
      <p></p>
      <div>
        <el-timeline>
          <el-timeline-item :timestamp="form.createDate" placement="top" color="blue">
            <span style="font-weight: bold;font-size: 14px;">新增草稿单</span>
            <el-card>
              <h4 style="font-weight: bold;">经办人发起申请</h4>
              <p class="p1"><span>{{form.preparedName}} </span><span>({{creatorDeptName}})</span><span
                  style="margin-left: 50px;">账号所属机构名称</span></p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item :timestamp="form.auditDate" placement="top" :color="auditColor">
            <span style="font-weight: bold;font-size: 14px;">审核</span>
            <el-card>
              <h4 style="font-weight: bold;" v-if="form.receiptsStatus == 1">已同意</h4>
              <h4 style="font-weight: bold;" v-if="form.receiptsStatus == 2">已拒绝</h4>
              <h4 style="font-weight: bold;" v-if="form.receiptsStatus == 3">待审核</h4>
              <h4 style="font-weight: bold;" v-if="form.receiptsStatus == 4">已撤销</h4>
              <div style="width: 450px;height: 40px;border: 1px solid #e7e7e7;background-color: #f0f0f0;padding:8px;">
                意见说明: {{form.auditReason}}
              </div>
              <p class="p1"><span></span><span>{{form.auditPersonName}}({{auditDeptName}})</span><span
                  style="margin-left: 50px;">账号所属机构名称</span></p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-button @click="cancel3()" style="margin-left: 485px;">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listAllot,
    getAllot,
    delAllot,
    addAllotH,
    addAllotD,
    updateAllot,
    updateAllotAsset,
    getTypeList,
    getEamList,
    deptByUserId,
    editStatus
  } from "@/api/eam-xl/allot";
  import {
    getInfo
  } from "@/api/login";

  export default {
    name: "Allot",
    data() {
      return {
        // 遮罩层
        loading: true,
        loading1: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        total2: 0,
        // 资产调拨表格数据
        allotList: [],
        // 弹出层标题
        title: "",
        title2: "选择资产",
        title3: "单据流水",
        title4: "系统提示",
        // 是否显示弹出层
        open: false,
        open2: false,
        open3: false,
        open4: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          allotOdd: null,
          isdel:1
        },
        // 表单参数
        form: {
          exportDept: undefined,
          foldDept: undefined,
          receiptsStatus: undefined,
          locationId: undefined,
          allotDate: undefined,
          auditReason:undefined
        },
        exportDeptList: [], //调出部门集合
        foldDeptList: [], //调入部门集合
        locationList: [], //存放位置集合
        eamList: [{}],
        assetList: [],
        typeList:[],
        asset: { //资产
          assetName: undefined,
          TypeId: undefined,
          locationId: undefined
        },
        chooseList:[],    //选择资产选中资产集合
        // 表单校验
        rules: {
          exportDept: [{
            required: true,
            message: "请选择调出部门",
            trigger: "change"
          }],
          foldDept: [{
            required: true,
            message: "请选择调入部门",
            trigger: "change"
          }],
          locationId: [{
            required: true,
            message: "请选择存放位置",
            trigger: "change"
          }],
          allotDate: [{
            required: true,
            message: "请选择调拨日期",
            trigger: "change"
          }],
        },
        user: {},
        roles: undefined, //权限控制
        creatorDeptName:undefined,
        auditDeptName:undefined,
        auditColor:undefined,
        exportStatusList:[],      //选中调拨单
        auditReason:undefined,
      };
    },
    created() {
      this.getList();
      getTypeList().then((res) => {
        this.locationList = res.locationList;
        this.exportDeptList = res.deptList;
        this.foldDeptList = res.deptList;
        this.typeList = res.typeList;
      })
      getInfo().then((res) => {
        this.user = res.user;
        this.roles = res.roles;
      });
    },
    methods: {
      /** 查询资产调拨列表 */
      getList() {
        this.loading = true;
        listAllot(this.queryParams).then(response => {
          this.allotList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.form = {};
        this.eamList = [{}];
        this.$refs["form"].resetFields();
      },
      cancel2() { //选择资产取消按钮
        this.open2 = false;
        this.asset = {};
      },
      cancel4() {
        this.open4 = false;
        this.auditReason = "";
      },
      // 表单重置
      reset() {

      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.exportStatusList = selection;
      },
      /** 新增按钮操作 */
      handleAdd() {
        //获取当前登录用户为创建人,制单人
        this.form.creator = this.user.userId;
        this.open = true;
        this.title = "新增调拨单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.title = "编辑调拨单";
        getAllot(row.allotId).then(res=>{
          this.form = res.data;
        })
        // if(this.form.assetlist.length == 0){
        //   this.form.assetlist = [{}];
        // }
        this.eamList = row.assetlist;
        this.open = true;
      },
      submit() { //选择资产确定按钮
        let _this = this;
        if (this.chooseList.length > 0) {
          if (this.eamList[0].assetCode == null) {
            this.eamList = this.chooseList;
          } else {
            if (this.eamList[this.eamList.length - 1].assetCode == null) {
              this.eamList.splice(this.eamList.length - 1, 1);
            }
            this.chooseList.forEach((item, index) => {
              this.eamList.push(item);
            })
          }
        }
        this.eamList.forEach((item, index) => {
          this.assetList.forEach((item1, index1) => {
            if (item.assetId == item1.assetId) {
              _this.assetList.splice(index1, 1);
            }
          })
        })
        this.eamList.forEach((item, index) => {
          this.eamList.forEach((item1, index1) => {
            if (item1.assetId == null) {
              this.eamList.splice(index1, 1);
            }
          })
        })
        if (this.eamList.length == 0) {
          this.eamList = [{}];
        }
        this.open2 = false;
      },
      /** 提交按钮 */
      submitForm() {
        if (this.form.receiptsStatus == null) { //添加
          this.addAllot();
        } else {                //修改
            if (this.roles == "common") {
              if (this.user.userId != this.form.prepared) {
                this.$message.warning("您没有此权限")
                return;
              }
            }
            if (this.form.receiptsStatus == 1) {
              this.$message.warning(this.form.loanCode + "单号已处理，无法修改");
              return;
            }
            if(this.form.receiptsStatus == 4){
              this.form.receiptsStatus = 3;
            }
            let _this = this;
            if (this.eamList[0].assetCode == null) {
                this.$message.warning("请选择需要调拨的资产");
                return;
              }
              if(this.form.exportDept == this.form.foldDept){
                this.$message.warning("选择信息有误");
                return;
              }
            _this.$refs["form"].validate((valid) => { //添加表单验证
                if (valid) {
                  _this.$modal.confirm('确认修改"' + _this.form.allotOdd + '"调拨单号的数据？').then(function() {
                      let obj = new Object();
                      //修改资产
                      _this.eamList.forEach((item, index) => {
                        item.locationId = _this.form.locationId;
                      })
                      obj.eamAllotH = _this.form;
                      obj.eamAssets = _this.eamList;
                      updateAllotAsset(obj).then(res=>{
                        _this.$message.success(res.msg);
                        _this.getList(); //变更单列表初始化
                        _this.cancel(); //重置数据
                      })
                  })
                }
              })
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let _this = this;
        if (this.roles == "common") {
          if (this.user.userId != this.form.prepared) {
            this.$message.warning("您没有此权限")
            return;
          }
        }
        this.$modal.confirm('是否删除调拨编号为"' + row.allotOdd + '"的数据项？').then(function() {
            row.isdel = 0;
            updateAllot(row).then(res=>{
              _this.$message.success(res.msg);
              _this.getList();
            })
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('eam/allot/export', {
          ...this.queryParams
        }, `allot_${new Date().getTime()}.xlsx`)
      },
      add() { //添加一行列表
        let loan = new Object();
        this.eamList.push(loan);
      },
      minus(index) { //删除一行列表
        if (this.eamList.length > 1) {
          this.assetList.push(this.eamList[index])
          this.eamList.splice(index, 1);
        }
      },
      open2Asset() { //选择资产弹框 ,搜索图标按钮
        this.open2 = true;
        this.loading1 = true;
        if (this.eamList[0].assetId != null) {
          getEamList(this.asset).then(res => {
            this.assetList = res.rows;
            this.eamList.forEach((item, index) => {
              this.assetList.forEach((item1, index1) => {
                if (item.assetId == item1.assetId) {
                  this.assetList.splice(index1, 1);
                }
              })
            })
            this.loading1 = false;
          })
        } else {
          getEamList(this.asset).then(res => {
            this.assetList = res.rows;
            this.loading1 = false;
          })
        }
      },
      assetSelectionChange(selection) { //选择资产复选框事件
        this.chooseList = selection
      },
      addAllot() { //添加调拨单
        let _this = this;
        if (this.eamList[0].assetCode == null) {
          this.$message.warning("请选择需要调拨的资产");
          return;
        }
        if(this.form.exportDept == this.form.foldDept){
          this.$message.warning("选择信息有误");
          return;
        }
      _this.$refs["form"].validate((valid) => { //添加表单验证
          if (valid) {
            //修改资产
            _this.eamList.forEach((item, index) => {
              item.locationId = _this.form.locationId;
            })
            _this.form.prepared = _this.user.userId;
            addAllotH(_this.form).then((res) => {
              _this.$modal.msgSuccess(res.msg);
            }).then(() => {
              addAllotD(_this.eamList);
              _this.cancel();
              _this.getList();
            })
          }
      })

      },
      hadReturn(row) { //撤回领用单
        //单据状态必须是待审核才可以撤回
        let _this = this;
        if(this.roles == "common"){
          if(this.user.userId != row.prepared){
            this.$message.warning("您没有此权限");
            return;
          }
        }
        this.$confirm('是否撤回' + row.allotOdd + "单号", '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //撤回
            row.receiptsStatus = 4;
            updateAllot(row).then((res) => {
              this.$message.success(res.msg);
              this.getList();
            })
        })
      },
      opneAudit(row) { //打开审核界面dialog
        this.form  = row;
        this.open4 = true;
      },
      audit(status) { //审核方法
        this.form.auditReason = this.auditReason;
        this.form.auditPerson = this.user.userId;
        this.form.receiptsStatus = status;
        this.form.auditDate = new Date().toLocaleString();
        this.open4 = false;
        updateAllot(this.form).then(res => {
          this.$message.success(res.msg);
          this.cancel4();
          this.getList();
        })
      },
       //单据流水Dialog
      flow(row) {
        this.form = row;
        let obj = new Object();
        if (row.receiptsStatus != 3) {
          this.auditColor = "blue";
        }
        obj.creatorId = row.prepared;
        obj.auditId = row.auditPerson;
        deptByUserId(obj).then(res=>{
          this.creatorDeptName = res.creatorDeptName;
          this.auditDeptName = res.auditDeptName;
        })
        this.open3 = true;
      },
      isExport(status){
        if( this.exportStatusList.length == 0){
            this.$message.warning("请选择调拨单")
        }else{
          this.exportStatusList.forEach((item,index)=>{
            item.isExportFold = status;
          })
          editStatus(this.exportStatusList).then(res=>{
            this.$message.success(res.msg)
            this.getList();
          })
        }

      }
    }
  };
</script>

<style>
  /* 单据状态 */
  .but1 {
    color: sandybrown;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ffdcbc;
    border: 1px solid sandybrown;
  }

  .but2 {
    color: #aa3800;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ff8d6a;
    border: 1px solid #ff8d6a;
  }

  .but3 {
    color: #4ab0f9;
    border-radius: 30px;
    font-size: 11px;
    background-color: #e6eff4;
    border: 1px solid #4ab0f9;
  }

  .but4 {
    color: #550000;
    border-radius: 30px;
    font-size: 11px;
    background-color: #d1d9dd;
    border: 1px solid #550000;
  }

  /* 搜索图片 */
  .img1 {
    height: 20px;
    position: absolute;
    z-index: 1;
    /* 设置图片的z-index值高于其他元素 */
    right: 15px;
    top: 18px;
    cursor: pointer;
    /* 将鼠标指针设置为手形 */
    transition: background-color 0.3s ease;
    /* 添加过渡效果 */
  }

  /* 入库单的加减图片 */
  .box_scope img {
    width: 18px;
    height: 18px;
    float: left;
    margin-left: 7px;
  }

  .box_scope img:hover {
    cursor: pointer;
  }


  /* 单据流水 */
  .img2 {
    height: 15px;
    display: block;
    margin-left: 140px;
    margin-top: -18.5px;
    cursor: pointer;
  }
</style>
